package edu.pku.sei.transformation.editor.controller.commands.node;

import org.eclipse.gef.commands.Command;

import edu.pku.sei.modeler.exceptions.FactoryNotFoundException;
import edu.pku.sei.modeler.model.common.AbstractFactory;
import edu.pku.sei.modeler.model.common.ModelRegistry;
import edu.pku.sei.modeler.model.core.MetaPackage;
import edu.pku.sei.transformation.editor.internal.TransformationEditorModelRoot;
import edu.pku.sei.transformation.editor.model.ModelPackage;
import edu.pku.sei.transformation.editor.model.Transformation;

public class TransformationCreateCommand extends Command {
	private MetaPackage pkg;
	private Transformation trans;

	public TransformationCreateCommand(Transformation transformation) {
		this.trans = transformation;
		this.pkg = TransformationEditorModelRoot.getTransformationPackage(trans
				.getModel());
	}

	@Override
	public boolean canExecute() {
		if (pkg == null || trans == null)
			return false;
		else
			return super.canExecute();
	}

	@Override
	public void execute() {
		try {
			AbstractFactory factory = ModelRegistry.getRegistry().getFactory(
					pkg.getModel());

			MetaPackage bindingPkg = (MetaPackage) factory.createElement(
					ModelPackage.__METAPACKAGE__, true);
			trans.setMetaPackage(bindingPkg);
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (FactoryNotFoundException e) {
			e.printStackTrace();
		}
		pkg.getOtherElements().add(trans);

	}

	@Override
	public void undo() {
		pkg.getOtherElements().remove(trans);
	}
}
